<template>
  <div v-if="!renderPreview || isDragPanel">

    <Select class="width-select" v-model="dataForm.province" value-key="value" filterable clearable placeholder="请选择省份"
            @on-change="changeProvince" @on-clear="changeProvince()" :disabled="disabled">
      <template v-for="item in provinces">
        <Option
            :key="item.v"
            :label="item.l"
            :value="item.v"
        > {{ item.l }}
        </Option>
      </template>
    </Select>
    <Select v-if="record.options.maxLevel >1 && (!record.options.oneByOne || dataForm.province)" class="width-select"
            v-model="dataForm.city" value-key="value" filterable clearable placeholder="请选择地市" @on-change="changeCity"
            @on-clear="changeCity()" :disabled="disabled">
      <template v-for="item in citys">
        <Option
            :key="item.v"
            :label="item.l"
            :value="item.v"
        > {{ item.l }}
        </Option>
      </template>
    </Select>
    <Select v-if="record.options.maxLevel > 2 && (!record.options.oneByOne || dataForm.city)" class="width-select"
            v-model="dataForm.district" value-key="value" filterable clearable placeholder="请选择区县"
            @on-change="changeDistrict" @on-clear="changeDistrict()" :disabled="disabled">
      <template v-for="item in districts">
        <Option
            :key="item.v"
            :label="item.l"
            :value="item.v"
        > {{ item.l }}
        </Option>
      </template>
    </Select>
  </div>
  <div v-else>
    <span>{{ models[record.model + '_label'] }}</span>
  </div>
</template>
<script>
import AreaData from './area.json';

export default {
  name: 'NLState',
  data() {
    return {
      areas: AreaData,
      provinces: [],
      citys: [],
      districts: [],
      dataForm: {
        province: '',
        city: '',
        district: '',
      },
    };
  },
  props: {

    value: {
      type: String,
    },
    record: {
      type: Object,
      required: true,
    },

    formConfig: {
      type: Object,
      required: false,
    },

    models: {
      type: Object,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },

    renderPreview: {
      type: Boolean,
      default: false,
    },

    isDragPanel: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.init();
  },
  watch: {
    value(val) {
      this.updateStateLabel(val);
    },
  },
  methods: {
    validator() {

    },

    updateStateLabel(val) {
      let address = [];

      const fs_ = (areas) => {
        areas.forEach(t => {
          if (t.v == val) {
            address.push(t.l);
          } else if (val.indexOf(t.v.replace(/0+$/, '')) == 0 && t.c && t.c.length > 0) {
            address.push(t.l);
            fs_(t.c);
          }
        });
      };

      fs_(AreaData);
      let separator = this.record.options.separator;
      if (separator == null || separator == undefined) {
        separator = '';
      }

      let str_ = '';
      if (this.record.options.showAllPath) {
        str_ = address.join(separator);
      } else {
        str_ = address.length > 0 ? address[address.length - 1] : '';
      }

      this.$set(this.models, this.record.model + '_label', str_);

    },
    init() {
      this.provinces = this.areas;


      const value = this.models[this.record.model];
      if (value) {


        this.dataForm.province = value.substr(0, 2) + '0000';
        this.dataForm.city = value.substr(0, 4) + '00';
        this.dataForm.district = value;

        this.changeProvince(this.dataForm.province, 1);
        this.changeCity(this.dataForm.city, 1);
        this.changeDistrict(this.dataForm.district, 1);

        if (!this.models[this.record.model + '_label']) {
          this.$nextTick(() => {
            this.updateStateLabel(value);
          });

        }

      }

    },
    getOrgs(pid) {
      return new Promise((resolve, reject) => {
        const ds = this.getOrgChild(pid);
        resolve(ds);
      });
    },
    getOrgChild(pid) {
      let ds = [];
      if (!pid) {

        return this.areas.map(t => {
          return {v: t.v, l: t.t};
        });
      }


      let datas = [];

      const fn = (data) => {


        for(const d of data){
          if(d.v==pid){
            datas=d.c;
            break;
          }else if(d.c && d.c.length>0){
            fn(d.c);
          }
        }
      };

      fn(this.areas);

      return datas;
    },
    changeProvince(v, type) {

      if (!type) {
        this.dataForm.city = '';
        this.dataForm.district = '';
      }

      this.districts = [];
      if (v) {
        this.getOrgs(v).then((data) => {
          this.citys = data;
        }).catch(() => {
          this.citys = [];
        });
      } else {
        this.citys = [];
      }

      if (!type) {
        if (this.record.options.maxLevel == 1) {
          this.value = v;
          this.$emit('input', v);
        } else {
          this.$emit('input', '');
          this.value = '';
        }
      }

    },
    changeCity(v, type) {

      if (!type) {
        this.dataForm.district = '';
      }

      if (v) {
        this.getOrgs(v).then((data) => {
          this.districts = data;
        }).catch(() => {
          this.districts = [];
        });

        if (!type) {
          if (this.record.options.maxLevel == 2) {
            this.$emit('input', v);
            this.value = v;
          } else {
            this.value = '';
            this.$emit('input', '');
          }

        }

      } else {
        this.districts = [];
        if (!type) {
          this.$emit('input', '');
        }

      }

    },
    changeDistrict(v, type) {
      if (type) {
        return;
      }
      if (v) {
        if (this.record.options.maxLevel == 3) {
          this.value = v;
          this.$emit('input', v);
        }
      } else {
        this.value = '';
        this.$emit('input', '');
      }
    },
  },
};
</script>
